package com.baoyang.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baoyang.entity.BaoyangPermission;
import com.baoyang.entity.BaoyangUser;
import com.baoyang.entity.vo.PermissionMenuReqVO;
import com.baoyang.service.BaoyangPermissionService;
import com.baoyang.tool.api.R;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/baoyang/permission")
public class BaoyangPermissionController {
    @Resource
    private BaoyangPermissionService baoyangPermissionService;

    @GetMapping("/list")
    public R list(HttpServletRequest request) {
        List<BaoyangPermission> permissions = baoyangPermissionService.listAll();
        return R.data(permissions);
    }

    @PostMapping("/add")
    public R add(@RequestBody PermissionMenuReqVO reqVO) {
        boolean success = baoyangPermissionService.save(reqVO);
        if (success) {
            return R.success("角色添加成功");
        } else {
            return R.fail("角色添加失败");
        }
    }

    /**
     * 删除权限
     */
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable("id") String id) {
        boolean success = baoyangPermissionService.removeById(id);
        if (success) {
            return R.success("角色删除成功");
        } else {
            return R.fail("角色删除失败");
        }
    }

    /**
     * 根据角色id获取菜单
     */
    @GetMapping("/getMenusByRoleId/{roleId}")
    public R getMenusByRoleId(@PathVariable("roleId") String roleId) {
        List<String> menuIds = baoyangPermissionService.getMenusByRoleId(roleId);
        return R.data(menuIds);
    }

    /**
     * 编辑角色
     */
    @PostMapping("/editRole")
    public R editRole(@RequestBody PermissionMenuReqVO reqVO) {
        boolean flag = baoyangPermissionService.editRole(reqVO);
        return R.status(flag);
    }

    /**
     * 分页
     */
    @GetMapping("/pageList")
    public R pageList(@RequestParam(defaultValue = "1") int pageNum,
                      @RequestParam(defaultValue = "10") int pageSize,
                      @RequestParam(required = false) String name) {
        Page<BaoyangPermission> page = new Page<>(pageNum, pageSize);
        IPage<BaoyangPermission> permissionPage = baoyangPermissionService.pageUserList(page, name);
        return R.data(permissionPage);
    }
}